{% extends "admin/base.html" %}

{% block title %}{{ title }}{% endblock %}
{% block page_title %}{{ title }}{% endblock %}

{% block content %}
<div class="card shadow">
    <div class="card-body">
        <form method="POST">
            {{ form.hidden_tag() }}
            
            <div class="row">
                <div class="col-md-8">
                    <!-- Title -->
                    <div class="mb-3">
                        {{ form.title.label(class="form-label") }}
                        {{ form.title(class="form-control") }}
                        {% if form.title.errors %}
                        <div class="text-danger">
                            {% for error in form.title.errors %}
                            <small>{{ error }}</small>
                            {% endfor %}
                        </div>
                        {% endif %}
                    </div>

                    <!-- Content -->
                    <div class="mb-3">
                        {{ form.content.label(class="form-label") }}
                        {{ form.content(class="form-control") }}
                        {% if form.content.errors %}
                        <div class="text-danger">
                            {% for error in form.content.errors %}
                            <small>{{ error }}</small>
                            {% endfor %}
                        </div>
                        {% endif %}
                        <div class="form-text">
                            支持 Markdown 语法，可以使用代码块、表格、链接等格式。
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <!-- Publish Settings -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">发布设置</h6>
                        </div>
                        <div class="card-body">
                            <div class="form-check mb-3">
                                {{ form.is_published(class="form-check-input") }}
                                {{ form.is_published.label(class="form-check-label") }}
                            </div>
                            <div class="form-check">
                                {{ form.is_featured(class="form-check-input") }}
                                {{ form.is_featured.label(class="form-check-label") }}
                            </div>
                        </div>
                    </div>

                    <!-- Category -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">分类</h6>
                        </div>
                        <div class="card-body">
                            {{ form.category_id(class="form-select") }}
                            {% if form.category_id.errors %}
                            <div class="text-danger">
                                {% for error in form.category_id.errors %}
                                <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <!-- Tags -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">标签</h6>
                        </div>
                        <div class="card-body">
                            {{ form.tags(class="form-control") }}
                            {% if form.tags.errors %}
                            <div class="text-danger">
                                {% for error in form.tags.errors %}
                                <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                            {% endif %}
                            <div class="form-text">
                                用逗号分隔多个标签
                            </div>
                        </div>
                    </div>

                    <!-- Excerpt -->
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">摘要</h6>
                        </div>
                        <div class="card-body">
                            {{ form.excerpt(class="form-control") }}
                            {% if form.excerpt.errors %}
                            <div class="text-danger">
                                {% for error in form.excerpt.errors %}
                                <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                            {% endif %}
                            <div class="form-text">
                                文章摘要，用于首页显示。留空则自动截取文章前200字符。
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Form Actions -->
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> 保存文章
                </button>
                <a href="{{ url_for('admin.posts') }}" class="btn btn-secondary">
                    <i class="fas fa-times"></i> 取消
                </a>
                {% if post %}
                <a href="{{ url_for('main.preview_post', slug=post.slug) }}" 
                   class="btn btn-info" target="_blank">
                    <i class="fas fa-eye"></i> 预览
                </a>
                {% endif %}
            </div>
        </form>
    </div>
</div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-eye"></i> 文章预览
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="previewContent" style="max-height: 70vh; overflow-y: auto; padding: 20px; border: 1px solid #dee2e6; border-radius: 0.375rem; background-color: #fff;">
                    <p class="text-muted">请输入内容进行预览</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
/* Markdown预览样式 */
#previewContent h1, #previewContent h2, #previewContent h3, 
#previewContent h4, #previewContent h5, #previewContent h6 {
    margin-top: 1.5rem;
    margin-bottom: 1rem;
    font-weight: 600;
    line-height: 1.25;
}

#previewContent h1 { font-size: 2rem; }
#previewContent h2 { font-size: 1.5rem; }
#previewContent h3 { font-size: 1.25rem; }

#previewContent p {
    margin-bottom: 1rem;
    line-height: 1.6;
}

#previewContent code {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 0.25rem;
    padding: 0.125rem 0.25rem;
    font-size: 0.875em;
    color: #d63384;
}

#previewContent pre {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 0.375rem;
    padding: 1rem;
    margin-bottom: 1rem;
    overflow-x: auto;
}

#previewContent pre code {
    background-color: transparent;
    border: none;
    padding: 0;
    color: inherit;
}

#previewContent blockquote {
    border-left: 4px solid #0d6efd;
    padding-left: 1rem;
    margin: 1rem 0;
    color: #6c757d;
    font-style: italic;
}

#previewContent ul, #previewContent ol {
    margin-bottom: 1rem;
    padding-left: 2rem;
}

#previewContent table {
    width: 100%;
    margin-bottom: 1rem;
    border-collapse: collapse;
}

#previewContent table th,
#previewContent table td {
    padding: 0.75rem;
    border: 1px solid #dee2e6;
}

#previewContent table th {
    background-color: #f8f9fa;
    font-weight: 600;
}

#previewContent img {
    max-width: 100%;
    height: auto;
    border-radius: 0.375rem;
    margin: 1rem 0;
}

#previewContent a {
    color: #0d6efd;
    text-decoration: none;
}

#previewContent a:hover {
    text-decoration: underline;
}

/* 数学公式样式 */
.math-inline {
    display: inline-block;
    margin: 0 2px;
}

.math-block {
    text-align: center;
    margin: 1rem 0;
    padding: 1rem;
    background-color: #f8f9fa;
    border-radius: 0.375rem;
    border: 1px solid #e9ecef;
}

/* MathJax 公式样式调整 */
.MathJax {
    font-size: 1.1em;
}

.MathJax_Display {
    margin: 1rem 0;
}
</style>
{% endblock %}

{% block extra_js %}
<!-- Markdown预览库 -->
<script src="https://cdn.jsdelivr.net/npm/marked@9.1.6/marked.min.js"></script>
<!-- MathJax 数学公式支持 -->
<script>
window.MathJax = {
    tex: {
        inlineMath: [['\\(', '\\)'], ['$', '$']],
        displayMath: [['\\[', '\\]'], ['$$', '$$']],
        processEscapes: true,
        processEnvironments: true,
        processRefs: true
    },
    options: {
        skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre'],
        ignoreHtmlClass: 'tex2jax_ignore',
        processHtmlClass: 'tex2jax_process'
    },
    startup: {
        ready: function () {
            console.log('MathJax is loaded, but not yet initialized');
            MathJax.startup.defaultReady();
            console.log('MathJax is initialized, and the initial typeset is queued');
        }
    }
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

<script>
// Markdown 预览功能
function previewMarkdown() {
    const contentField = document.querySelector('textarea[name="content"]');
    const content = contentField ? contentField.value : '';
    const preview = document.getElementById('previewContent');
    
    if (content.trim()) {
        // 使用marked库解析Markdown
        try {
            let html = marked.parse(content);
            
            // 处理数学公式
            html = processMathFormulas(html);
            
            preview.innerHTML = html;
            
            // 等待MathJax加载完成后重新渲染数学公式
            if (window.MathJax) {
                MathJax.typesetPromise([preview]).then(() => {
                    console.log('MathJax渲染完成');
                }).catch((err) => {
                    console.error('MathJax渲染错误:', err);
                });
            } else {
                // 如果MathJax还没加载，等待加载完成
                const checkMathJax = setInterval(() => {
                    if (window.MathJax) {
                        clearInterval(checkMathJax);
                        MathJax.typesetPromise([preview]).catch((err) => {
                            console.error('MathJax渲染错误:', err);
                        });
                    }
                }, 100);
                
                // 10秒后停止检查
                setTimeout(() => clearInterval(checkMathJax), 10000);
            }
        } catch (error) {
            preview.innerHTML = '<div class="alert alert-warning">Markdown解析错误: ' + error.message + '</div>';
        }
    } else {
        preview.innerHTML = '<p class="text-muted">请输入内容进行预览</p>';
    }
    
    const modal = new bootstrap.Modal(document.getElementById('previewModal'));
    modal.show();
}

// 处理数学公式的JavaScript函数
function processMathFormulas(html) {
    // 先处理块级数学公式 $$ ... $$
    html = html.replace(/\$\$([^$]+)\$\$/g, '<div class="math-block">$$$$1$$</div>');
    
    // 再处理行内数学公式 \( ... \)
    html = html.replace(/\\\(([^)]+)\\\)/g, '<span class="math-inline">\\($1\\)</span>');
    
    // 最后处理行内数学公式 $ ... $ (但不在$$块中)
    html = html.replace(/(?<!\$)\$([^$]+)\$(?!\$)/g, '<span class="math-inline">$$1$</span>');
    
    return html;
}

// 添加预览按钮
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');
    const submitBtn = form.querySelector('button[type="submit"]');
    
    const previewBtn = document.createElement('button');
    previewBtn.type = 'button';
    previewBtn.className = 'btn btn-outline-info ms-2';
    previewBtn.innerHTML = '<i class="fas fa-eye"></i> 预览';
    previewBtn.onclick = previewMarkdown;
    
    submitBtn.parentNode.insertBefore(previewBtn, submitBtn.nextSibling);
    
    // 添加实时预览功能（可选）
    const contentField = document.querySelector('textarea[name="content"]');
    if (contentField) {
        let previewTimeout;
        contentField.addEventListener('input', function() {
            clearTimeout(previewTimeout);
            previewTimeout = setTimeout(function() {
                // 可以在这里添加实时预览逻辑
            }, 1000);
        });
    }
});
</script>
{% endblock %}

